<?php

namespace backend\controllers;

use common\models\AuthAssignmentModel;
use Yii;
use common\models\AuthItemModel;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\pagination;
use backend\models\ItemForm;
use yii\helpers\Json;
use backend\models\Admin;
use yii\web\Response;
use yii\helpers\ArrayHelper;

/**
 * ItemController implements the CRUD actions for AuthItemModel model.
 */
class ItemController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function actionIndex()
    {
        $model    = new AuthItemModel();
        //分页
        $curPage  = Yii:: $app-> request->get( 'page',1);
        $pageSize = Yii::$app->params['pageSize']['item'];
        //搜索
        $type   = Yii:: $app-> request->get( 'type', '');
        $value  = Yii:: $app-> request->get( 'value', '');
        $search = ($type&&$value)?[ 'like',$type,$value]: '';
        //查询语句
        $query  = $model->find()->orderBy( 'created_at DESC');
        $data   = $model->getPages($query,$curPage,$pageSize,$search);
        $pages  = new Pagination([ 'totalCount' =>$data[ 'count'], 'pageSize' => $pageSize]);

        return $this->render('index',['pages'=>$pages,'data'=>$data]);
    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
       $model = new ItemForm();
       //设置场景
       $model->setScenario(ItemForm:: SCENARIOS_CREATE);
       //加载数据以及调用创建方法
       if ($model->load(Yii:: $app-> request->post())) {
           if($model->validate()){
               $model->addItem();
               return $this->redirect([ 'view', 'id' => $model->name]);
           }
       }
       return $this->render( 'create', [
           'model' => $model,
       ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->name]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    public function actionDelete()
    {
        $model = new ItemForm();
        $model->setScenario(ItemForm:: SCENARIOS_DELETE);
        $model-> name = Yii:: $app-> request->post( 'id');
        $res =  $model->romoveItem();
        if(!$res)
            return Json:: encode(['status'=>false,'msg'=>'删除失败！']);
        return Json::encode(['status' =>true]);
    }

    protected function findModel($id)
    {
        if (($model = AuthItemModel::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    //角色管理列表
    public function actionRoule()
    {
        $get_data = AuthItemModel::find()->where(['type' => 1])->all();
        return $this->render('roule', ['model' => $model = new ItemForm(), 'pro_data' => $get_data]);
    }

    public function actionAddroule()
    {
        if(Yii::$app->request->isPost){
            $model = new ItemForm();
            //设置场景
            $model->setScenario(ItemForm:: SCENARIOS_CREATE);
            $data = Yii::$app->request->post();
            if($model->load($data)){
                if($model->validate()){
                    $model->addItem(); //添加角色
                    if(isset($data['node'])){ //赋予权限
                       $model->addItemChild($data['node'], $model->name);
                    }
                    return $this->redirect([ 'roule']);
                }
            }
        }
        $roule_data_arr = self::actionDefautroule();
        return $this->render('add_roule', ['model' => $model = new ItemForm(), 'roule_data_arr' => $roule_data_arr]);
    }

    public function actionSetroule()
    {
        if(Yii::$app->request->get('name')){
            $get_name = Yii::$app->request->get('name');
            $authManager = \Yii::$app->authManager;
            $roleNodes = $authManager->getPermissionsByRole($get_name);
            $roleNodes = array_keys($roleNodes);
            $roule_data_arr = self::actionDefautroule();
            $model = new ItemForm();
            $model['name'] = $get_name;
            return $this->render('setroule', [
                'model'          => $model,
                'roule_data_arr' => $roule_data_arr,
                'name'           => $get_name,
                'roule_node'     => $roleNodes
            ]);
        }
    }

    public function actionAddsetrole(){
        if(Yii::$app->request->isPost){
            $data= Yii::$app->request->post();
            if(isset($data['node'])){ //赋予权限
                $auth = Yii::$app->authManager;
                $role = $auth->getRole($data['name']);
                if (!$role) {
                   $role = $auth->createRole($data['name']);
                   $auth->add($role);
                }
                //分配权限
                $oldPermissions = [];
                if ($auth->getPermissionsByRole($role->name)) {
                    $oldPermissions = ArrayHelper::getColumn($auth->getPermissionsByRole($role->name), 'name');
                }
                $newPermissions = array_values($data['node']);
                $newPermissions = array_combine($newPermissions, $newPermissions);
                //计算交集
                $intersection   = array_intersect($newPermissions, $oldPermissions);
                //需要增加的权限
                $newPermissions = array_diff($newPermissions, $intersection);
                //需要删除的权限
                $oldPermissions = array_diff($oldPermissions, $intersection);

                $model = new ItemForm();
                $model->addItemChild($newPermissions, $role->name);
                $model->removeItemChild($oldPermissions, $role->name);
            }
            return $this->redirect([ 'roule']);
        }
    }

    protected static function actionDefautroule()
    {
        //获取默认数据-渲染页面
        $get_data = AuthItemModel::find()->where(['type' => 2])->orWhere(['type' => 0])->asArray()->all();
        $count = count($get_data);
        $num = 0;
        $str = '';
        for($i= 0; $i<$count; $i++){
            if(!strstr($get_data[$i]['name'], '/')){
                $num++;
                $new_arr[$num]['name']        = $get_data[$i]['name'];
                $new_arr[$num]['description'] = $get_data[$i]['description'];
                $str .= $get_data[$i]['name'] . ',';
            }
        }
        //组装-权限显示格式
        $check = 0;
        foreach($new_arr as $k => $v){
            foreach($get_data as $getkey => $getval){
                if( strstr($getval['name'], $v['name']) && strlen($getval['name']) != strlen($v['name'])){
                    $check++;
                    $new_arr[$k]['child'][$check] = [
                        'name' => $getval['name'],
                        'description' =>  $getval['description'],
                    ];
                }
                if(!strstr($getval['name'], 'item') && !strstr($getval['name'], 'message')){
                    $low_arr[$getval['name']] = [
                         'name'        => $getval['name'],
                         'description' =>  $getval['description'],
                    ];
                }
            }
            $check = 0;
        }
        return array_merge((array)$new_arr, (array)$low_arr);
    }

    public function actionRoledel($name)
    {
       $result = [];
       $auth = Yii::$app->authManager;
       $role = $auth->getRole($name);
       if ($role) {
           $auth->remove($role);
       }
       $result['status']  = 1;
       $result['message'] = '删除成功';
       return $this->redirect(['item/roule']);
    }

    //添加管理员
    public function actionAddadmin(){
        $model = new Admin(['scenario' => 'addadmin']);
        $get_role = AuthItemModel::find()->where(['type' => 1])->asArray()->all();
        if(!$get_role) return false;  //没有任何角色
        $admin_role = [];

        if(Yii::$app->request->post('Admin')){
            $data = Yii::$app->request->post();
            //判断是已存在用户修改 还是新用户
            if(isset($data['Admin']['uid']) && $uid = $data['Admin']['uid']){
                //老用户
                $model->uid = $uid;
                $admin_info = Admin::find()->where(['id' => $uid])->asArray()->one();
                $admin_name = Admin::find()->where(['username' => $data['Admin']['username']])->andWhere(['!=', 'id', $uid])->asArray()->all();
                if($admin_name){
                    Yii::$app->session->hasFlash('info', '用户名已经存在');
                    Yii::$app->end();
                }
                $admin_password = ($data['Admin']['password'] == substr($admin_info['password'], 0, 6))? $admin_info['password']: md5($data['Admin']['password']);
                //执行修改
                Admin::updateAll([
                    'username' => $data['Admin']['username'],
                    'password' => $admin_password,
                    'useremail'=> $data['Admin']['useremail'],
                ], 'id = :id', [':id' => $uid]);
            }else{
                //新用户
                $data       = Yii::$app->request->post();
                if($model->load($data) && $model->validate()){
                    $admin_name = Admin::find()->where(['username' => $data['Admin']['username']])->asArray()->all();
                    if($admin_name){
                        Yii::$app->session->hasFlash('info', '用户名已经存在');
                        Yii::$app->end();
                   }
                    $model = new Admin();
                    $model->username  = $data['Admin']['username'];
                    $model->useremail = $data['Admin']['useremail'];
                    $model->password  = md5($data['Admin']['password']);
                    $model->login_time  = time();
                    $model->create_time = time();
                    $model->login_ip    = ip2long(Yii::$app->request->userIP);
                    if($model->save()<0){
                        Yii::$app->session->setFlash('info', '添加管理员失败');
                        Yii::$app->end();
                    }
                    $model->uid = $model->id;
                }
            }
            //给角用户删除或赋予角色
            if(isset($data['role'])){
                $auth = Yii::$app->authManager;
                $auth->revokeAll($uid);
                foreach($data['role'] as $rolename){
                   if($role = $auth->getRole($rolename)){
                       $auth->assign($role, $model->uid);
                   }
                }
                return $this->redirect(['item/admininfo']);
            }
        }

        if($uid = Yii::$app->request->get('uid')){
            if(!is_numeric($uid)) return false;
            $user_info = Admin::find()->where(['id' => $uid])->asArray()->all();
            if(!$user_info) return false; //没有该用户
            $model->username  = $user_info[0]['username'];
            $model->useremail = $user_info[0]['useremail'];
            $model->password  = substr($user_info[0]['password'], 0,6);
            $model->repass    = substr($user_info[0]['password'], 0,6);
            $model->uid       = $uid;
            $admin_role = AuthAssignmentModel::find()->where(['user_id' => $uid])->asArray()->all();
            if($admin_role && is_array($admin_role)){
                foreach($admin_role as $k => $v){
                    $admin_role[$k] = $v['item_name'];
                }
            }
        }
        return $this->render('add_admin', [
            'model' => $model,
            'admin_role' => $admin_role,
            'role_info' => $get_role,
        ]);
    }

    //删除管理员
    public function actionDel(){
        $id = Yii::$app->request->post('id');
        $user = Admin::findOne( $id );
        if(!$user){
            $result['status']  = 0;
            $result['message'] = '未找到此用户';
        }else{
            $user->delete();
            $auth = Yii::$app->authManager;
            $auth->revokeAll($id);
            $result['status'] = 1;
            $result['message'] = '保存成功';
        }
        return $this->renderJson($result);
    }

    //管理员列表
    public function actionAdmininfo()
    {
        $admin_data = Admin::find()->all();
        return $this->render('admin_index', ['admin_data' => $admin_data, 'model' => new Admin()]);
    }

    protected function renderJson($params = [])
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return $params;
    }


}
